import { DeleteOutlined, UploadOutlined } from '@ant-design/icons';
import {
  Button,
  Col,
  Form,
  Input,
  InputNumber,
  Modal,
  message,
  Popconfirm,
  Row,
  Upload,
  type UploadProps,
} from 'antd';
import { useEffect, useState } from 'react';
import { uploadFile } from '@/services/file';
import { gutter } from '../const/keys';
import type { RecordType } from './AddModal';
import styles from './AddRecord.modules.less';

const getDataUrl = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
};

type Props = {
  data?: RecordType;
  onOk: (item: Omit<RecordType, 'projectId'>) => void;
  onClose: (reflash?: boolean) => void;
};
let timer: string | number | NodeJS.Timeout | undefined;
const App = (props: Props) => {
  const { data, onClose = () => {}, onOk = () => {} } = props;
  const [addForm] = Form.useForm();
  const [uploading, setUploading] = useState(false);
  const [fileList, setFileList] = useState<any[]>([]);

  // ✅ 上传函数：并发上传多个文件
  const uploadStart = async (newFiles: File[]) => {
    setUploading(true);
    try {
      const uploadedFiles = await Promise.all(
        newFiles.map(async (file) => {
          if (!file.type.startsWith('image/')) {
            message.error(`文件 ${file.name} 不是图片`);
            return null;
          }
          const dataUrl = await getDataUrl(file);
          const formData = new FormData();
          formData.append('file', file);

          const { data, success, msg } = await uploadFile(formData);
          if (success) {
            return { ...data, dataUrl, uid: data.id };
          } else {
            message.error(msg || `上传 ${file.name} 失败`);
            return null;
          }
        }),
      );

      const validFiles = uploadedFiles.filter(Boolean);
      setFileList((prev) => [...prev, ...validFiles]);
    } finally {
      setUploading(false);
    }
  };

  // ✅ Upload 配置
  const uploadProps: UploadProps = {
    multiple: true,
    showUploadList: false,
    accept: 'image/*',
    beforeUpload: (_file, list) => {
      clearTimeout(timer);
      timer = setTimeout(() => {
        uploadStart(list);
      }, 10);
      return false; // 阻止自动上传
    },
  };

  // ✅ 提交
  const addRecord = async () => {
    await addForm.validateFields();
    const values = addForm.getFieldsValue();

    const picList = fileList.map((file) => ({
      ...file,
      id: file.uid || file.id,
      dataUrl: file.dataUrl,
    }));

    const submitValues = {
      ...values,
      paymentRecordAmount: values.paymentRecordAmount * 100,
      picList,
    };

    onOk(submitValues);
    addForm.resetFields();
    setFileList([]);
  };

  // ✅ 初始化数据
  useEffect(() => {
    if (data) {
      addForm.setFieldsValue({
        paymentRecordAmount: data.paymentRecordAmount / 100,
        paymentRecordDesc: data.paymentRecordDesc,
      });
      setFileList(
        data.picList?.map((item) => ({ ...item, uid: item.id })) || [],
      );
    } else {
      addForm.resetFields();
      setFileList([]);
    }
  }, [data]);

  return (
    <Modal
      title="新增付款记录"
      open={true}
      maskClosable={false}
      closable={!uploading}
      okButtonProps={{
        disabled: uploading,
      }}
      cancelButtonProps={{
        disabled: uploading,
      }}
      onOk={addRecord}
      onCancel={() => onClose(false)}
    >
      <Form form={addForm} labelCol={{ span: 6 }}>
        <Form.Item
          label="款项阶段描述"
          name="paymentRecordDesc"
          rules={[{ required: true, message: '请输入款项阶段描述' }]}
        >
          <Input placeholder="请输入款项阶段描述" />
        </Form.Item>
        <Form.Item
          label="付款金额"
          name="paymentRecordAmount"
          rules={[{ required: true, message: '请输入付款金额' }]}
        >
          <InputNumber
            style={{ width: '100%' }}
            placeholder="请输入付款金额"
            precision={2}
          />
        </Form.Item>
        <Form.Item
          label="付款凭证"
          name="voucher"
          rules={[{ required: true, message: '请上传付款凭证' }]}
        >
          <Row gutter={[gutter, gutter]}>
            {fileList.length > 0 && (
              <Col span={24}>
                <Row gutter={[gutter, gutter]}>
                  {fileList.map((file) => (
                    <Col key={file.uid}>
                      <div className={styles.img}>
                        <img src={file.dataUrl || file.filePath} alt="" />
                        <div className={styles.deleteIcon}>
                          <Popconfirm
                            title="确定要删除吗？"
                            onConfirm={() =>
                              setFileList((prev) =>
                                prev.filter((item) => item.uid !== file.uid),
                              )
                            }
                          >
                            <DeleteOutlined />
                          </Popconfirm>
                        </div>
                      </div>
                    </Col>
                  ))}
                </Row>
              </Col>
            )}
            <Col span={24}>
              <Upload {...uploadProps}>
                <Button
                  loading={uploading}
                  icon={<UploadOutlined />}
                  disabled={uploading}
                >
                  上传
                </Button>
              </Upload>
            </Col>
          </Row>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default App;
